from django.core.management.base import BaseCommand, CommandError
from django.forms.models import model_to_dict

from scoreboard.boardv1.models import *
import json
import os, sys

"""
      ring = models.ForeignKey(Ring)
  order = models.IntegerField()
  event_type = models.ForeignKey(EventType)
  level = models.ForeignKey(Level)
  age_group = models.ForeignKey(AgeGroup)
  gender = models.ForeignKey(Gender)
  shortcode = models.CharField(max_length=6)
  completed = models.BooleanField()  # Is false if ongoing
  ongoing = models.BooleanField()    # Is false if completed
  num_competitors = models.IntegerField()"""

DEFAULT_EXPECTED_FILES = {
  'competitors.json': [Competitor, {

  }], 'events.json': [Event, {
      'ring_id': 'ring',
      'ring_order': 'order',
      'event_type_num': 'event_type',
      'level_chr': 'level'
  }], 'event_types.json': [EventType, {

  }], 'levels.json': [Level, {
      'chr': 'code',
      'str': 'name'
  }], 'age_groups.json': [AgeGroup, {
      'chr': 'code',
      'str': 'name'
  }], 'genders.json': [Gender, {
      'chr': 'code',
      'str': 'name'
  }], 'placings.json': [Placing, {

  }]
}

INT_FILEDS = [
    'ring_id', 'event_type_num', 'num_competitors', 'ring_order'
]

class Command(BaseCommand):
  args = '<path-to-json-files>'
  help = 'Imports data'

  def handle(self, *args, **options):
    if not args:
      expected_files = DEFAULT_EXPECTED_FILES
    elif not os.path.exists(args[0]):
      print '%s does not exist' % args[0]
    elif os.path.isdir(args[0]):
      expected_files = dict([(os.path.join(args[0], k), v)
          for k, v in DEFAULT_EXPECTED_FILES.iteritems()])
    else:
      expected_files = {args[0]: DEFAULT_EXPECTED_FILES[args[0]]}
    for expected_file, table_mapping in expected_files.iteritems():
      print 'Processing %s' % expected_file
      table, mapping = table_mapping
      filename = os.path.join(args[0], expected_file)
      if os.path.exists(filename):
        file_data = json.load(open(filename))

        for item in file_data:
          # Check all of the items add if needed, update otherwise.
          try:
            transformed_data = dict([
                (to_name, item[from_name] if from_name not in INT_FILEDS else int(item[from_name]))
                 for from_name, to_name in mapping.iteritems()])
            for k in transformed_data.keys():
              if isinstance(transformed_data[k], str) and transformed_data[k].endswith('_chr'):
                transformed_data[k] = ord(transformed_data[k])
            print 'f'
            if 'id' in item:
              transformed_data['id'] = int(item['id'])
            elif 'ring_order' in item:
              transformed_data['id'] = int(item['ring_order'])
            else:
              transformed_data['id'] = ord(item['chr'])
          except Exception as e:
            print 'Exception while processing %s\n%s' % (item, e)
            raise e
          try:
            lookup = table.objects.get(id=transformed_item['id'])
          except Exception:
            print '%s did not exist, creating.' % transformed_data
            table_item = table(**transformed_data)
            table_item.save()
          else:
            table_item = lookup
            table_item_as_dict = model_to_dict(
                table_item, fields=[], exclude=['id'])
            if table_item_as_dict != transformed_data:
              print '%s existed but needed to update.' % table_item
              table_item.save()
            else:
              print '%s existed but did not need to update.' % item
      else:
        print 'File %s did not exist, skipping' % filename